<?php
namespace App\Http\Controllers\Manage\Steam\Game;

use App\Http\Controllers\Manage\CommonController;
use App\Model\Steam\SteamGame;
use App\Model\Steam\SteamGameTag;
use App\Model\Steam\SteamGameTagMap;
use App\Model\Steam\SteamGameCategory;
use App\Model\Steam\SteamGameCategoryMap;
class SteamGameController extends CommonController
{
    /**
     * 查看steam游戏
     * @return mixed
     */
    public function index()
    {
        $field = [
            'id' => '编号',
            'title' => '标题',
            'price' => '价格',
            'discount_price' => '优惠价格',
            'discount_start' => '优惠开始时间',
            'discount_end' => '优惠结束时间',
//            'introduction' => '简单介绍',
            'issue_date' => '发行日期',
            'is_free' => '是否免费',
            'is_discount' => '是否优惠',
            'is_new' => '是否最新',
            'is_recommend' => '是否推荐',
            'is_hot' => '是否热门',
            'is_windows' => 'Windows游戏',
            'is_macos' => 'MacOs游戏',
            'is_linux' => 'Linux游戏',
            'rank' => '顺序',

        ];
        $viewData = [];
        $viewData['title'] = 'Steam游戏管理';
        $viewData['range'] = [
            'is_free' => YN(),
            'is_discount' => YN(),
            'is_new' => YN(),
            'is_recommend' => YN(),
            'is_hot' => YN(),
            'is_windows' => YN(),
            'is_macos' => YN(),
            'is_linux' => YN(),
        ];
        # 查询字段
        $viewData['field'] = $field;
        # 列表操作菜单
        $viewData['option_title'] = [
            'plus' => [
                'title' => '发布新游戏',
                'route' => route('manage.steam.game.resource.create')
            ]
        ];
        # 行表操作菜单
        $page = $this->request->input('page', 1);
        $viewData['option_row'] = [
            'edit' => [
                'title' => '编辑',
                'route' => 'manage.steam.game.resource.edit',
                'param' =>   [
                    'page' => $page
                ]
            ],
            'trash' => [
                'title' => '删除',
                'route' => 'manage.steam.game.resource.destroy'
            ],
            'tag' => [
                'title'=>'标签',
                'load'=>'manage.steam.game.tag'
            ],
            'category' => [
                'title'=>'分类',
                'load'=>'manage.steam.game.category'
            ],
        ];
        # 页面模态对话框
        $viewData['option_modal'] = [
            'trash' => [
                'method' => 'DELETE',
                'title' => '删除游戏',
                'msg' => '确定要删除该游戏吗'
            ],
        ];
        # 查询记录
        $steamGame = SteamGame::where('is_delete', 0);
        $viewData['list'] = $this->constraintSelect($steamGame, $field);
        # 渲染视图
        return view('manage.table', $viewData);
    }

    /**
     * 添加steam游戏页面
     * @return mixed
     */
    public function create()
    {
        # 表单元素
        $param = [];
        $param['title'] = [
            'name' => '标题',
            'type' => 'text',
            'col' => '12'
        ];
        $param['is_windows'] = [
            'name' => 'Windows游戏',
            'type' => 'select',
            'col' => '3',
            'range' =>YN()
        ];
        $param['is_macos'] = [
            'name' => 'MacOs游戏',
            'type' => 'select',
            'col' => '3',
            'range' =>YN()
        ];
        $param['is_linux'] = [
            'name' => 'Linux游戏',
            'type' => 'select',
            'col' => '3',
            'range' =>YN()
        ];
        $param['is_recommend'] = [
            'name' => '是否推荐',
            'type' => 'select',
            'col' => '3',
            'range' =>YN()
        ];

        $param['is_new'] = [
            'name' => '是否最新',
            'type' => 'select',
            'col' => '3',
            'range' =>YN()
        ];
        $param['discount_start'] = [
            'name' => '优惠开始时间',
            'type' => 'datetimepicker',
            'col' => '3'
        ];
        $param['discount_end'] = [
            'name' => '优惠结束时间',
            'type' => 'datetimepicker',
            'col' => '3'
        ];


        $param['issue_date'] = [
            'name' => '发行日期',
            'type' => 'datetimepicker',
            'col' => '3'
        ];
        $param['price'] = [
            'name' => '价格',
            'type' => 'text',
            'col' => '3'
        ];
        $param['is_discount'] = [
            'name' => '是否优惠',
            'type' => 'select',
            'col' => '3',
            'range' =>YN()
        ];
        $param['discount_price'] = [
            'name' => '优惠价格',
            'type' => 'text',
            'col' => '3'
        ];
        $param['rank'] = [
            'name' => '顺序',
            'type' => 'text',
            'col' => '3'
        ];

        $param['is_free'] = [
            'name' => '是否免费',
            'type' => 'select',
            'col' => '3',
            'range' =>YN()
        ];
        $param['is_hot'] = [
            'name' => '是否热门',
            'type' => 'select',
            'col' => '3',
            'range' =>YN()
        ];
        $param['introduction'] = [
            'name' => '简单介绍',
            'type' => 'textarea',
            'col' => '12',
            'row' => '3'
        ];
        $param['thumb'] = [
            'type' => 'thumb',
            'col' => '3',
            'name' => '游戏缩略预览图（建议256×256像素）',
            'accept' => 'image',
//            'value' => $this->domain . $this->path['steam_game_thumb'] . $goods->goods_thumb,
            'ratio' => '1',
        ];

        foreach ($param as $key => $value) {
            $param[$key]['value'] = $this->request->old($key);
        }
        if($param['is_free']['value'] == null) $param['is_free']['value'] = 0;
        if($param['is_discount']['value'] == null) $param['is_discount']['value'] = 0;
        if($param['is_new']['value'] == null) $param['is_new']['value'] = 0;
        if($param['is_recommend']['value'] == null) $param['is_recommend']['value'] = 0;
        if($param['is_hot']['value'] == null) $param['is_hot']['value'] = 0;
        if($param['is_windows']['value'] == null) $param['is_windows']['value'] = 0;
        if($param['is_macos']['value'] == null) $param['is_macos']['value'] = 0;
        if($param['is_linux']['value'] == null) $param['is_linux']['value'] = 0;

        $viewData = [];
        $viewData['title'] = '发布新游戏';
        $viewData['form'] = $this->form($param);
        $viewData['form_url'] = route('manage.steam.game.resource.store');
        $viewData['form_method'] = 'POST';
        $viewData['form_button'] = [
            'back' => [
                'name' => '返回游戏列表',
                'type' => 'button',
                'route' => route('manage.steam.game.resource.index')
            ],
            'reset' => [
                'name' => '重置',
                'type' => 'reset'
            ],
            'submit' => [
                'name' => '提交',
                'type' => 'submit',
            ]
        ];
        return view('manage.form', $viewData);
    }
    public function tag($id)
    {

        $tagValue = SteamGameTagMap::where('game_id', $id)->lists('tag_id')->implode(',');

        $tag = SteamGameTag::keyName();

        # 表单元素配置
        $param = [
            'tag' => [
                'type' => 'checkbox',
                'col' => '12',
                'name' => '标签名称',
                'range' => $tag,
                'value' => $tagValue,
            ],
        ];
        $form = $this->form($param);
        return view('manage.lib.form')
            ->with('form', $form)
            ->with('form_url', route('manage.steam.game.tag', ['id' => $id]))
            ->with('form_method', 'POST')
            ->with('form_title', '游戏标签');

    }

    public function tagForm($id)
    {
        $tag = $this->request->input('tag');
        if ($tag) {
            # 查询已有关联记录
            $map = SteamGameTagMap::where('game_id', $id)->lists('tag_id')->toArray();
            # 过滤已有的关联数据，并获取需要删除的关联数据
            # 需要添加是数据
            $add = array_diff($tag, $map);
            # 执行添加记录
            $data = array();
            foreach ($add as $val) {
                $data[] = [
                    'game_id' => $id,
                    'tag_id' => $val

                ];
            }
            SteamGameTagMap::insert($data);
            # 需要删除的数据
            $del = array_diff($map, $tag);
            # 执行删除记录
            SteamGameTagMap::where('game_id', $id)->whereIn('tag_id', $del)->delete();
            return redirect()->back()->with('success', '修改成功!');
        }
        return redirect()->back()->with('error', '修改失败!');
    }

    public function category($id)
    {

        $categoryValue = SteamGameCategoryMap::where('game_id', $id)->lists('category_id')->implode(',');

        $category = SteamGameCategory::keyName();

        # 表单元素配置
        $param = [
            'category' => [
                'type' => 'checkbox',
                'col' => '12',
                'name' => '标签名称',
                'range' => $category,
                'value' => $categoryValue,
            ],
        ];
        $form = $this->form($param);
        return view('manage.lib.form')
            ->with('form', $form)
            ->with('form_url', route('manage.steam.game.category', ['id' => $id]))
            ->with('form_method', 'POST')
            ->with('form_title', '游戏分类');

    }

    public function categoryForm($id)
    {
        $category = $this->request->input('category');
        if ($category) {
            # 查询已有关联记录
            $map = SteamGameCategoryMap::where('game_id', $id)->lists('category_id')->toArray();
            # 过滤已有的关联数据，并获取需要删除的关联数据
            # 需要添加是数据
            $add = array_diff($category, $map);
            # 执行添加记录
            $data = array();
            foreach ($add as $val) {
                $data[] = [
                    'game_id' => $id,
                    'category_id' => $val

                ];
            }
            SteamGameCategoryMap::insert($data);
            # 需要删除的数据
            $del = array_diff($map, $category);
            # 执行删除记录
            SteamGameCategoryMap::where('game_id', $id)->whereIn('category_id', $del)->delete();
            return redirect()->back()->with('success', '修改成功!');
        }
        return redirect()->back()->with('error', '修改失败!');
    }
    /**
     *
     * 创建游戏页面
     *
     * @param  $request
     * @return mixed
     */
    public function store()
    {
        $this->request->flash();
        if (!$this->request->has('title')) {
            return redirect()->back()->with('error', '请填写标题');
        }
        if (!$this->request->has('price')) {
            return redirect()->back()->with('error', '请填写游戏价格');
        }
        if (!$this->request->has('issue_date')) {
            return redirect()->back()->with('error', '请填写发行日期');
        }
        if (!$this->request->has('introduction')) {
            return redirect()->back()->with('error', '请填写简单介绍');
        }
        if (!$this->request->has('rank')) {
            return redirect()->back()->with('error', '请填写顺序');
        }
        # 检查是否上传了缩率预览图
        if (!$this->request->has('thumb')) {
            return redirect()->back()->with('error', '游戏缩略图必须上传!');
        }

        $thumb = $this->request->input('thumb');
        $thumb = $this->uploadBase64Image($thumb, 'steam_game_thumb');
        if (!$thumb) {
            return redirect()->back()->with('error', '游戏缩略图上传失败!');
        }
        # 插入新数据
        $steamGame = new SteamGame();
        $steamGame->thumb = $thumb;
        $steamGame->title = $this->request->input('title');
        $steamGame->is_free = $this->request->input('is_free');
        $steamGame->issue_date = $this->request->input('issue_date');
        $steamGame->price = $this->request->input('price');
        $steamGame->discount_price = $this->request->input('discount_price');
        if(!empty($this->request->input('discount_start')))
          $steamGame->discount_start = $this->request->input('discount_start');
        if(!empty($this->request->input('discount_end')))
          $steamGame->discount_end = $this->request->input('discount_end');
        $steamGame->introduction = $this->request->input('introduction');
        $steamGame->is_discount = $this->request->input('is_discount');
        $steamGame->rank = $this->request->input('rank');
        $steamGame->is_new = $this->request->input('is_new');
        $steamGame->is_recommend = $this->request->input('is_recommend');
        $steamGame->is_hot = $this->request->input('is_hot');
        $steamGame->is_windows = $this->request->input('is_windows');
        $steamGame->is_macos = $this->request->input('is_macos');
        $steamGame->is_linux = $this->request->input('is_linux');

        $steamGame->create_user = $this->user['id'];
        if ($steamGame->save()) {
            # 创建成功后跳转到公众号详细介绍编辑页
            return redirect()->route('manage.steam.game.resource.index')->with('success', '游戏创建成功!');
        }
        return redirect()->back()->with('error', '游戏创建失败!');
    }

    /**
     * 修改游戏页面
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {
        $steamGame = SteamGame::find($id);
        # 表单元素
        $param = [];
        $param['title'] = [
            'name' => '标题',
            'type' => 'text',
            'col' => '12',
            'value' => $steamGame->title
        ];
        $param['is_windows'] = [
            'name' => 'Windows游戏',
            'type' => 'select',
            'col' => '3',
            'range' =>YN(),
            'value' => $steamGame->is_windows
        ];
        $param['is_macos'] = [
            'name' => 'MacOs游戏',
            'type' => 'select',
            'col' => '3',
            'range' =>YN(),
            'value' => $steamGame->is_macos
        ];
        $param['is_linux'] = [
            'name' => 'Linux游戏',
            'type' => 'select',
            'col' => '3',
            'range' =>YN(),
            'value' => $steamGame->is_linux
        ];
        $param['is_recommend'] = [
            'name' => '是否推荐',
            'type' => 'select',
            'col' => '3',
            'range' =>YN(),
            'value' => $steamGame->is_recommend
        ];

        $param['is_new'] = [
            'name' => '是否最新',
            'type' => 'select',
            'col' => '3',
            'range' =>YN(),
            'value' => $steamGame->is_new
        ];
        $param['discount_start'] = [
            'name' => '优惠开始时间',
            'type' => 'datetimepicker',
            'col' => '3',
            'value' => $steamGame->discount_start
        ];
        $param['discount_end'] = [
            'name' => '优惠结束时间',
            'type' => 'datetimepicker',
            'col' => '3',
            'value' => $steamGame->discount_end
        ];


        $param['issue_date'] = [
            'name' => '发行日期',
            'type' => 'datetimepicker',
            'col' => '3',
            'value' => $steamGame->issue_date
        ];
        $param['price'] = [
            'name' => '价格',
            'type' => 'text',
            'col' => '3',
            'value' => $steamGame->price
        ];
        $param['is_discount'] = [
            'name' => '是否优惠',
            'type' => 'select',
            'col' => '3',
            'range' =>YN(),
            'value' => $steamGame->is_discount
        ];
        $param['discount_price'] = [
            'name' => '优惠价格',
            'type' => 'text',
            'col' => '3',
            'value' => $steamGame->discount_price
        ];
        $param['rank'] = [
            'name' => '顺序',
            'type' => 'text',
            'col' => '3',
            'value' => $steamGame->rank
        ];

        $param['is_free'] = [
            'name' => '是否免费',
            'type' => 'select',
            'col' => '3',
            'range' =>YN(),
            'value' => $steamGame->is_free
        ];
        $param['is_hot'] = [
            'name' => '是否热门',
            'type' => 'select',
            'col' => '3',
            'range' =>YN(),
            'value' => $steamGame->is_hot
        ];
        $param['introduction'] = [
            'name' => '简单介绍',
            'type' => 'textarea',
            'col' => '12',
            'row' => '3',
            'value' => $steamGame->introduction
        ];
        $param['thumb'] = [
            'type' => 'thumb',
            'col' => '3',
            'name' => '游戏缩略预览图（建议256×256像素）',
            'accept' => 'image',
           'value' => $this->domain . $this->path['steam_game_thumb'] . $steamGame->thumb,
            'ratio' => '1',
        ];
        foreach ($param as $key => $value) {
            if ($this->request->old($key)) $param[$key]['value'] = $this->request->old($key);
        }
        $viewData = [];
        $viewData['title'] = '修改游戏信息';
        $viewData['nav'] = $this->navTab('steam_game', 'main', ['id' => $id]);
        $viewData['form'] = $this->form($param);
        $page = $this->request->input('page', 1);
        $viewData['form_url'] = route('manage.steam.game.resource.update', ['id' => $id, 'page' => $page]);
        $viewData['form_method'] = 'PUT';
        $viewData['form_button'] = [
            'back' => [
                'name' => '返回游戏列表',
                'type' => 'button',
                'route' => route('manage.steam.game.resource.index')
            ],
            'reset' => [
                'name' => '重置',
                'type' => 'reset'
            ],
            'submit' => [
                'name' => '提交',
                'type' => 'submit',
            ]
        ];
        # 渲染视图
        return view('manage.form', $viewData);
    }

    /**
     *
     * 修改游戏操作
     *
     * @param $id
     * @return mixed
     */
    public function update($id)
    {
        $steamGame = SteamGame::find($id);
        $this->request->flash();
        if (!$this->request->has('title')) {
            return redirect()->back()->with('error', '请填写标题');
        }
        if (!$this->request->has('price')) {
            return redirect()->back()->with('error', '请填写游戏价格');
        }
        if (!$this->request->has('issue_date')) {
            return redirect()->back()->with('error', '请填写发行日期');
        }
        if (!$this->request->has('introduction')) {
            return redirect()->back()->with('error', '请填写简单介绍');
        }

        if (!$this->request->has('rank')) {
            return redirect()->back()->with('error', '请填写顺序');
        }

        # 修改预览图
        $thumb = null;
        if ($this->request->has('thumb')) {
            $thumb = $this->request->input('thumb');
            $thumb = $this->uploadBase64Image($thumb, 'steam_game_thumb');
            if (!$thumb) {
                return redirect()->back()->with('error', '游戏缩略图上传失败!');
            }
        }
        $steamGame->thumb = $thumb;
        $steamGame->title = $this->request->input('title');
        $steamGame->is_free = $this->request->input('is_free');
        $steamGame->issue_date = $this->request->input('issue_date');
        $steamGame->price = $this->request->input('price');
        $steamGame->discount_price = $this->request->input('discount_price');
        if(!empty($this->request->input('discount_start')))
            $steamGame->discount_start = $this->request->input('discount_start');
        if(!empty($this->request->input('discount_end')))
            $steamGame->discount_end = $this->request->input('discount_end');
        $steamGame->introduction = $this->request->input('introduction');
        $steamGame->is_discount = $this->request->input('is_discount');
        $steamGame->rank = $this->request->input('rank');
        $steamGame->is_new = $this->request->input('is_new');
        $steamGame->is_recommend = $this->request->input('is_recommend');
        $steamGame->is_hot = $this->request->input('is_hot');
        $steamGame->is_windows = $this->request->input('is_windows');
        $steamGame->is_macos = $this->request->input('is_macos');
        $steamGame->is_linux = $this->request->input('is_linux');

        $steamGame->update_user = $this->user['id'];
        if (!$steamGame->save()) {
            return redirect()->back()->with('error', '游戏修改成功');
        }
        $page = $this->request->input('page', 1);
        $param = [
            'page' => $page
        ];
        return redirect()->route('manage.steam.game.resource.index', $param)->with('success', '游戏修改成功');
    }
    /**
     * 删除游戏
     * @param $id
     * @return mixed
     */
    public function destroy($id)
    {
        $steamGame = SteamGame::find($id);
        $steamGame->is_delete = 1;
        $steamGame->update_user = $this->user['id'];
        $this->log(json_encode('manage:' . $this->user['id'] . ' remove steamGame:' . $id . ' time:' . currentTime()), 'info', 'steamGame_destroy');
        if ($steamGame->save()) {
            return redirect()->back()->with('success', '游戏删除成功!');
        }
        return redirect()->back()->with('error', '游戏删除失败!');
    }
}